package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.employee.domain.Employee;
import com.ruoyi.employee.mapper.EmployeeMapper;
import com.ruoyi.guest.domain.Guest;
import com.ruoyi.guest.mapper.GuestMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.impl.SysRoleServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.util.CollectionUtils;

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Set;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Slf4j
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private GuestMapper guestMapper;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 手机号一键登录
     */
    // 在SysLoginService中新增方法
    public String phoneLogin(String phoneNumber) {
        // 校验手机号格式
        if (!validatePhoneNumber(phoneNumber)) {
            throw new IllegalArgumentException("手机号格式不合法");
        }

        // 1. 查询手机号对应的用户
        SysUser user = userMapper.selectByPhoneNumber(phoneNumber);

        // 2. 自动注册逻辑（如需要）
        if (user == null) {
            user = new SysUser();
            // user.setUserName("微信用户_" + phoneNumber);
            // 参考wxLogin中的用户名生成逻辑
            user.setUserName("wx_" + phoneNumber.substring(7) + "_" + System.currentTimeMillis() % 10000);
            user.setNickName("手机用户_" + phoneNumber);
            user.setPassword(SecurityUtils.encryptPassword("123456"));
            user.setPhonenumber(phoneNumber);
            // 设置默认角色ID（需确认系统角色ID）
            user.setRoleIds(new Long[]{104L}); // 参考wxLogin方法中的默认角色
            user.setUserType("00");
            user.setStatus("0");
            user.setCreateBy(SecurityUtils.getUsername());
            user.setCreateTime(DateUtils.getNowDate());

            userService.insertUser(user);

            // +++ 关键修改：创建员工并关联用户 +++
            Employee employee = new Employee();
            employee.setName(user.getUserName());
            // employee.setJobCode(generateJobCode(openId)); // 不用初始化员工编号
            employee.setStatus("0");
            employee.setCreateTime(DateUtils.getNowDate());

            // 设置关联字段
            employee.setUserId(user.getUserId()); // 关联新用户ID
            // 插入员工
            employeeMapper.insertEmployee(employee);
        }
        // 3. 创建登录用户对象
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setUserId(user.getUserId());
        loginUser.setPermissions(permissionService.getMenuPermission(user));

        // 4. 生成token
        return tokenService.createToken(loginUser);
    }

    // 新增手机号格式校验
    private boolean validatePhoneNumber(String phoneNumber) {
        // 简单校验示例
        return StringUtils.isNotEmpty(phoneNumber) &&
                phoneNumber.matches("^1[3-9]\\d{9}$");
    }


    /**
     * 微信登录
     *
     * @return
     */
    public String wxLogin(String openId, String sessionKey){
        //字符串转json
//        JSONObject jsonObject = JSONObject.parseObject(decryptResult);
//        String openId = jsonObject.getString("openId");

        log.info("openid:", openId);
        System.out.println("openId"+openId);

        //根据openid查询用户信息
        SysUser wxUser = userMapper.selectWxUserByOpenId(openId);
        SysUser user = new SysUser();

        // 默认昵称和头像（对于新用户）
        String nickName = "微信用户";
        String avatarUrl = "";

        //获取nickName
//        String nickName = jsonObject.getString("nickName"); // 获取真实昵称
//        log.info("nickName:", nickName);
//        if (StringUtils.isEmpty(nickName)) {
//            nickName = "微信用户";
//        } else if (nickName.length() > 30) {
//            nickName = nickName.substring(0, 30); // 截断超长昵称
//        }

//        String avatarUrl = jsonObject.getString("avatarUrl"); // 获取真实头像
//        log.info("avatarUrl:", avatarUrl);
//        if (StringUtils.isNotEmpty(avatarUrl)) {
//            // 确保不超过数据库字段长度
//            if (avatarUrl.length() > 100) {
//                // 方案1：截断URL
//                avatarUrl = avatarUrl.substring(0, 100);
//
//                // 方案2：使用压缩图URL（推荐）
//                // avatarUrl = compressWechatAvatar(avatarUrl);
//            }
//        } else {
//            avatarUrl = "";
//        }
        // String avatarUrl = "";
        //还可以获取其他信息......

        //根据openid查询用户信息
//        SysUser wxUser = userMapper.selectWxUserByOpenId(openId);
//        SysUser user = new SysUser();

        if (wxUser == null) {
            // 创建新用户
            user.setUserName(generateWxUsername(openId)); // 使用openId生成唯一用户名
            user.setNickName(nickName);
            user.setAvatar(avatarUrl);
//            user.setNickName(StringUtils.isNotEmpty(nickName) ? nickName : "微信用户" + openId);
//            user.setAvatar(StringUtils.isNotEmpty(avatarUrl) ? avatarUrl : "");

            user.setOpenId(openId);
            // user.setUnionId(unionId);
            // user.setUserType("00"); // 微信用户类型
            Long[] roleIds = {104L};
            user.setRoleIds(roleIds);// 微信登录用户初始角色分配为"用户"

            user.setStatus("0"); // 账号状态正常
            user.setPassword(SecurityUtils.encryptPassword("123456")); // 设置固定初始‍密码
            user.setCreateTime(DateUtils.getNowDate());

            // 使用服务层方法处理角色关联
            userService.insertUser(user);

            // +++ 关键修改：创建顾客并关联用户 +++
            Guest guest = new Guest();
            guest.setUsername(generateWxUsername(openId));
            guest.setNickname(nickName);
//            guest.setNickname(StringUtils.isNotEmpty(nickName) ? nickName : "微信用户");
            // 与用户密码一致
            guest.setPassword(user.getPassword());
            guest.setAvatarUrl(avatarUrl);
//            guest.setAvatarUrl(StringUtils.isNotEmpty(avatarUrl) ? avatarUrl : "");
            guest.setWechatOpenid(openId);
            // 解决手机号唯一约束问题
            guest.setMobile(null);

            guest.setCreateTime(DateUtils.getNowDate());
            // 设置关联字段
            guest.setUserId(user.getUserId());
            // 插入顾客
            guestMapper.insertGuest(guest);

            // +++ 关键修改：创建员工并关联用户 +++
            Employee employee = new Employee();
            employee.setName(nickName);
//            employee.setName(StringUtils.isNotEmpty(nickName) ? nickName : "微信用户");
            // employee.setJobCode(generateJobCode(openId)); // 不用初始化员工编号
            employee.setStatus("0");
            employee.setCreateTime(DateUtils.getNowDate());
            // 设置关联字段
            employee.setUserId(user.getUserId()); // 关联新用户ID
            // 插入员工
            employeeMapper.insertEmployee(employee);
        } else {
            user = wxUser;
            user.setUpdateTime(DateUtils.getNowDate());

            // 1. 获取用户角色ID列表
            List<Long> roleIdsList = roleService.selectRoleListByUserId(user.getUserId());

            // 2. 检查用户是否有角色
            if (CollectionUtils.isEmpty(roleIdsList)) {
                // 用户确实没有角色，设置默认角色
                user.setRoleIds(new Long[]{104L});
                log.warn("用户{}({})无角色，已设置默认角色{}",
                        user.getUserId(), user.getUserName(), "104L");
            } else {
                // 3. 将数据库中的角色ID设置回user对象
                user.setRoleIds(roleIdsList.toArray(new Long[0]));
                log.debug("用户{}({})保留现有角色{}",
                        user.getUserId(), user.getUserName(), Arrays.toString(user.getRoleIds()));
            }


            // +++ 新增：检查并补充顾客信息 +++
            Guest existingGuest = guestMapper.selectGuestByUserId(user.getUserId());
            if (existingGuest == null) {
                Guest newGuest = new Guest();
                newGuest.setUsername(user.getUserName());
                newGuest.setNickname(user.getNickName());
//                newGuest.setNickname(StringUtils.isNotEmpty(nickName) ? nickName : user.getNickName());
                // 密码保持不变
                newGuest.setPassword(user.getPassword());
                newGuest.setAvatarUrl(user.getAvatar());

//                newGuest.setAvatarUrl(StringUtils.isNotEmpty(avatarUrl) ? avatarUrl : user.getAvatar());
                newGuest.setWechatOpenid(openId);
                newGuest.setMobile(null);

                newGuest.setCreateTime(DateUtils.getNowDate());
                newGuest.setUserId(user.getUserId());
                guestMapper.insertGuest(newGuest);
                log.info("为用户{}创建了新的顾客信息", user.getUserId());
            }

            // +++ 新增：检查并补充员工信息 +++
            Employee existingEmployee = employeeMapper.selectEmployeeByUserId(user.getUserId());
            if (existingEmployee == null) {
                Employee newEmployee = new Employee();
                newEmployee.setName(user.getNickName());
//                newEmployee.setName(StringUtils.isNotEmpty(nickName) ? nickName : user.getNickName());
                newEmployee.setStatus("0");
                newEmployee.setCreateTime(DateUtils.getNowDate());
                newEmployee.setUserId(user.getUserId());
                employeeMapper.insertEmployee(newEmployee);
                log.info("为用户{}创建了新的员工信息", user.getUserId());
            }

            // 更新用户信息
            userService.updateUser(user); // 使用服务层更新
        }

        //组装token信息
        LoginUser loginUser = new LoginUser();
        loginUser.setOpenId(openId);
        //如果有的话设置
        loginUser.setUser(user);
        loginUser.setUserId(user.getUserId());

        // 新增：查询并设置 permissions
        Set<String> permissions = permissionService.getMenuPermission(user);
        loginUser.setPermissions(permissions); // 显式设置 permissions

        // 生成token
        return tokenService.createToken(loginUser);
    }

    // 生成基于openId的唯一用户名
    private String generateWxUsername(String openId) {
        String prefix = "wx_";
        // 取openId后8位 + 时间戳后4位
        String suffix = openId.length() > 8 ?
                       openId.substring(openId.length() - 8) :
                       openId;
        long timestamp = System.currentTimeMillis();
        return prefix + suffix + "_" + (timestamp % 10000);
    }

    // 生成随机工号
    private String generateJobCode(String openId) {
        String prefix = "rs_";
        // 取openId后4位 + 时间戳后4位
        String suffix = openId.length() > 4 ?
                openId.substring(openId.length() - 4) :
                openId;
        long timestamp = System.currentTimeMillis();
        return prefix + suffix + "_" + (timestamp % 10000);
    }


    // 生成安全随机密码
    private String generateSecurePassword() {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(12);

        for (int i = 0; i < 12; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }

    // 微信头像压缩
    private String compressWechatAvatar(String originalUrl) {
        // 微信头像URL压缩规则：添加参数 /132 表示132x132尺寸
        if (originalUrl.contains("thirdwx.qlogo.cn")) {
            return originalUrl.replace("/0", "/132");
        }
        // 其他图床处理逻辑
        return originalUrl.length() > 100 ?
               originalUrl.substring(0, 100) :
               originalUrl;
    }


    //生成随机用户名，数字和字母组成,
    public static String getStringRandom(int length) {

        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
